package cn.cubic.sys.modular.subjectinfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.cubic.core.exception.ServiceException;
import cn.cubic.core.factory.PageFactory;
import cn.cubic.core.pojo.page.PageResult;
import cn.cubic.sys.modular.subjectinfo.entity.SubjectInfo;
import cn.cubic.sys.modular.subjectinfo.mapper.SubjectInfoMapper;
import cn.cubic.sys.modular.subjectinfo.model.param.SubjectInfoParam;
import cn.cubic.sys.modular.subjectinfo.service.SubjectInfoService;
import cn.cubic.sys.modular.subjectinfo.enums.SubjectInfoExceptionEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 课程信息表 服务实现类
 */
@Service
public class SubjectInfoServiceImpl extends ServiceImpl<SubjectInfoMapper, SubjectInfo> implements SubjectInfoService {

    @Override
    public PageResult<SubjectInfo> page(SubjectInfoParam subjectInfoParam) {

        // 构造条件
        LambdaQueryWrapper<SubjectInfo> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<SubjectInfo> list(SubjectInfoParam subjectInfoParam) {

        // 构造条件
        LambdaQueryWrapper<SubjectInfo> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public void add(SubjectInfoParam subjectInfoParam) {

        // 将dto转为实体
        SubjectInfo subjectInfo = new SubjectInfo();
        BeanUtil.copyProperties(subjectInfoParam, subjectInfo);

        this.save(subjectInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(SubjectInfoParam subjectInfoParam) {
        this.removeById(subjectInfoParam.getId());
    }

    @Override
    public void edit(SubjectInfoParam subjectInfoParam) {

        // 根据id查询实体
        SubjectInfo subjectInfo = this.querySubjectInfo(subjectInfoParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(subjectInfoParam, subjectInfo);

        this.updateById(subjectInfo);
    }

    @Override
    public SubjectInfo detail(SubjectInfoParam subjectInfoParam) {
        return this.querySubjectInfo(subjectInfoParam);
    }



    /**
     * 获取课程信息表
     */
    private SubjectInfo querySubjectInfo(SubjectInfoParam subjectInfoParam) {
        SubjectInfo subjectInfo = this.getById(subjectInfoParam.getId());
        if (ObjectUtil.isEmpty(subjectInfo)) {
            throw new ServiceException(SubjectInfoExceptionEnum.NOT_EXISTED);
        }
        return subjectInfo;
    }
}